<template>
    <div class="nav">
        <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item :to="{ path: '/control' }">商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>套餐详情</el-breadcrumb-item>
        </el-breadcrumb>
    </div>
    <!-- 搜索 -->
    <div class="search">
        <h3>筛选条件</h3>
        <div class="search-details">
            <el-button type="danger" size="small" @click="delproduct(ids)">全部清除</el-button>
            <label>
                <span>搜索</span>
                <el-input placeholder="请输入产品名" clearable size="small" v-model="search.name"/>
            </label>
            <label>
                <span>分类搜索</span>
                <el-select placeholder="请选择分类" size="small" clearable v-model="search.category">
                    <el-option v-for="item in catelist" :key="item.id" :label="item.title" :value="item.id" />
                </el-select>
            </label>
            <el-button size="small" @click="add('add')">新增</el-button>

        </div>
    </div>
    <!-- 内容 -->
    <div class="container">
        <el-config-provider :locale="zhCn">
            <!-- 当选择项发生改变时触发，有一个参数会返回所有勾选的数据 -->
        <el-table :data="pagesData" style="width: 100%" max-height="500px" @selection-change="changeId">
            <el-table-column type="selection" width="55"  v-model="ids"/>
            <el-table-column fixed prop="name" label="套餐名称" width="100" /> 
            <el-table-column prop="price" label="套餐价格" width="100" />
            <el-table-column prop="price" label="套餐原价" width="100" />
            <el-table-column fixed prop="image" label="图片" width="100">
                <template #default="scope">
                    <img :src="scope.row.image" alt="" style="width: 50px;height: 50px;">
                </template>
            </el-table-column>
            <el-table-column prop="description" label="描述信息" width="200" />
            <el-table-column prop="copies" label="套餐份额" width="100" />
            <el-table-column prop="details" label="套餐详情" width="200" />
            <el-table-column prop="category_id" label="套餐分类" width="100" />
            <el-table-column prop="status" label="0 停售 1 起售" width="150" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="add('edit',scope.row)">修改</el-button>
                    <el-button type="danger" size="small" @click="delproduct([scope.row.id])">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

    </el-config-provider>
    </div>
    <!-- 分页 -->
    <div class="page">
        <el-config-provider :locale="zhCn">
            <el-pagination 
            v-model:current-page="pages.current" 
            :page-sizes="[ 4, 6, 8]" 
            layout="total,sizes,prev, pager, next"
            :total="pages.pagetotal" 
            v-model:page-size='pages.pagesize' />
        </el-config-provider>
    </div>
    <!-- 弹出的页面 -->
    <el-dialog v-model="visible" width="400px"  @close="close()">
        <template #header>
            <div class="my-header">
                <h4>{{ filte === 'add' ? '新增套餐信息':'修改套餐信息'}}</h4>
                <el-form :rules="rules" :model="info" ref="formrules" label-width="100px" >
                <el-form-item label="套餐名称" prop="name">
                    <el-input placeholder="请输入套餐名" clearable v-model="info.name" size="small">
                    </el-input>
                </el-form-item>
                <el-form-item label="套餐价格" prop="price">
                    <el-input-number v-model="info.price" :min="0" :max="999" @change="handleChange" />
                </el-form-item>
                <el-form-item label="套餐原价" prop="old_price">
                        <el-input-number v-model="info.old_price" :min="0" :max="100" @change="handleChange" />
                    </el-form-item>
                <el-form-item label="套餐类型" prop="category_id">
                    <el-select placeholder="请选择分类" size="small" clearable v-model="info.category_id" >
                    <el-option v-for="item in catelist" :key="item.id" :label="item.title" :value="item.id" />
                </el-select>
                </el-form-item>
                <el-form-item label="套餐描述" prop="description">
                    <el-input v-model="info.description" placeholder="请输入套餐描述" clearable size="small" type="textarea">
                    </el-input>
                </el-form-item>
                <el-form-item label="套餐份额" prop="copies">
                    <el-input-number v-model="info.copies" :min="0" :max="999" @change="handleChange" />
                </el-form-item>
                <el-form-item label="套餐详情" prop="details">
                    <el-input v-model="info.details" placeholder="请输入套餐描述" clearable size="small" type="textarea">
                    </el-input>
                </el-form-item>
                <el-form-item label="是否起售" prop="status">
                    <el-switch v-model="info.status" />
                </el-form-item>
                <el-form-item label="产品图片" prop="image">
                    <el-upload class="avatar-uploader"
                            action="#"
                            ref = "file"
                            :limit="1"
                            :http-request="uploadImg"
                            :on-change="ChangeUpdate"
                            :before-upload="beforeAvatarUpload"
                            >
                            <img class="avatar" :src="info.image" v-if="info.image"/>
                            <svg>
                                <use xlink:href="#icon-enlarge"></use>
                            </svg>
                    </el-upload>
                </el-form-item>
                <div style="text-align: center;" > <el-button type="success" @click="changeProduct(formrules)"  >提交</el-button></div>
               
            </el-form>
            </div>
        </template>
    </el-dialog>

</template> 
<script setup>

import { ref,computed } from 'vue'
import { useRouter } from 'vue-router'
import http from '../tools/axios';
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
const router = useRouter()
// 分类数据
const catelist = ref([
    { id: 1, title: '单人套餐' },
    { id: 2, title: '精选套餐' },
    { id: 3, title: '双人套餐' },
    { id: 4, title: '店长推荐套餐' }, 
    { id: 5, title: '火锅丸滑' },
    { id: 6, title: '调料蘸料' }, 
    { id: 7, title: '川渝特色' }, 
])
// 产品详情数据
const product = ref([
    { id: 1,name:'酸菜鱼套餐',price: '18.9', category_id:1,copies:90,details:'老坛酸菜鱼必选，水晶粉丝、龙口粉丝、精制土豆粉三选一',
    image:'https://tse2-mm.cn.bing.net/th/id/OIP-C.v2RCDRg3fnr3H5ofDn2E1QHaKB?w=115&h=180&c=7&r=0&o=5&category_id=1.7', 
    description: '活鱼现切，大刀鱼片，酸爽脆嫩',status:'1'},
    { id: 2,name:'青虾滑2',price: '18.9', category_id:2,copies:90,details:'老坛酸菜鱼必选，水晶粉丝、龙口粉丝、精制土豆粉三选一',
    image:'https://ts2.cn.mm.bing.net/th?id=OIP-C.v2RCDRg3fnr3H5ofDn2E1QHaKB&w=214&h=290&c=8&rs=1&qlt=90&o=6&category_id=3.1&rm=2', 
    description: '口感弹韧，爽滑，鲜甜', status:'1'},
    { id: 3,name:'青虾滑3',price: '18.9', category_id:1,copies:90,details:'老坛酸菜鱼必选，水晶粉丝、龙口粉丝、精制土豆粉三选一',
    image:'https://ts2.cn.mm.bing.net/th?id=OIP-C.v2RCDRg3fnr3H5ofDn2E1QHaKB&w=214&h=290&c=8&rs=1&qlt=90&o=6&category_id=3.1&rm=2', 
    description: '口感弹韧，爽滑，鲜甜', status:'1'},
    { id: 4,name:'青虾滑4',price: '18.9', category_id:2,copies:90,details:'老坛酸菜鱼必选，水晶粉丝、龙口粉丝、精制土豆粉三选一',
    image:'https://ts2.cn.mm.bing.net/th?id=OIP-C.v2RCDRg3fnr3H5ofDn2E1QHaKB&w=214&h=290&c=8&rs=1&qlt=90&o=6&category_id=3.1&rm=2', 
    description: '口感弹韧，爽滑，鲜甜', status:'1'},
])
// 查询菜品接口
const getDate = () => {
    http.get('/product/inquire_taocan').then((res) => {
        console.log(res.data);
        product.value = res.data.data
    })
}
const getlist = () => {
    http.get('/product/catelist1').then((res) => {
        console.log(res.data);
        catelist.value = res.data.data
    })
}

getlist()
getDate()


// 搜索数据
const search = ref({
    name: '',
    category:''
})

const ids = ref([])
const changeId = (value)=>{
    ids.value = value.map(item=>{
        return item.id
    })
}


const searchData = computed(()=>{
    let arr = product.value.filter(item=>{
        return item.name.includes(search.value.name)&&
        (search.value.category ? item.category_id === search.value.category : true)
    })

    // JSON.parse(JSON.stringify(arr))防止原对象受到污染
    return JSON.parse(JSON.stringify(arr)).map(item=>{
        for(var i=0;i<catelist.value.length;i++){
            if(catelist.value[i].id === item.category_id){
                item.category_id = catelist.value[i].title
        }
    }
        return item
    })
})
// 页码数据
const pages = ref(
    { current: 1, pagesize: 4, pagetotal: searchData.value.length }
)

// 分页功能
const pagesData = computed(()=>{
    pages.value.pagetotal = searchData.value.length;
    const start = (pages.value.current - 1) * pages.value.pagesize;
    const end  = pages.value.current * pages.value.pagesize;
    console.log(start,end);
    return searchData.value.slice(start,end)
})


// 删除事件
const delproduct = (id) => {
    if (confirm('你确定要删除吗？')) {
        http.post('/product/delete_taocan', { ids: id }).then((res) => {
            console.log(res.data);
        })
    }
    getDate()
}

// 弹窗功能
const visible = ref(false)
const info = ref({})

const rules = ref({
    name: [
        { required: true, message: '请输入套餐名', trigger: 'blur' },
      
    ],
    price: [
        { required: true, message: '请输入套餐价格', trigger: 'blur' },
       
    ],
    category_id: [
        { required: true, message: '请输入套餐类型', trigger: 'blur' },
       
    ],
    description: [
        { required: true, message: '请输入套餐描述', trigger: 'blur' },
       
    ], 
    details: [
        { required: true, message: '请输入套餐详情', trigger: 'blur' },
       
    ], 
    copies:[
        { required: true, message: '请输入套餐份额', trigger: 'blur' },
    ],
    status:[
        { required: true, message: '请输入是否启用', trigger: 'blur' },
    ]

})

const file = ref()

// 表单提交
const formrules = ref(null)
const filte =ref('add')
// 新增事件
const add=(str,obj)=>{
    visible.value = true;
    filte.value = str
    // 防止数据粘连
    if(obj) info.value = {...obj}
}
// 关闭弹窗 清除表单数据
const close = () => {
    file.value.clearFiles()
    info.value = {}
}
const changeProduct = (formEl)=>{

   if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            if (info.value.status === true) info.value.status = 1
                else info.value.status = 0
            
            if (filte.value === 'add') {

                http.post('/product/add_taocan', info.value).then(res => {
                    ElMessage({
                        showClose: true,
                        message: '添加成功',
                        type: 'success',
                    })
                })
                getDate()
                
            } else {
               catelist.value.map(item=>{
                if(item.title == info.value.category_id){
                    info.value.category_id = item.id
                }
                return item
               })
                http.post('/product/update_taocan', info.value).then(res => {
                    ElMessage({
                        showClose: true,
                        message: '修改成功',
                        type: 'success',
                    })
                })
                getDate()
            }
          
            visible.value = false
        } else {
            ElMessage({
                showClose: true,
                message: '请补全信息重新添加',
                type: 'warning',
            })
        }
    })
    
}

// 图片上传事件
const beforeAvatarUpload=(rawFile)=>{
    const format = rawFile.type.split('/').pop().toLowerCase();
    console.log(rawFile);
    let isIMG = ['png','jpg','webp','jpeg','svg']
    if(!isIMG.includes(format)){
        return ElMessage({
            showClose: true,
            message: '上传图片只能是 png、jpg、webp、jpeg、svg 格式!',
            type: 'warning',
        })
    }
    if(rawFile.size>1024*1024*20){
        return ElMessage({
            showClose: true,
            message: '上传图片大小不能超过 20MB!',
            type: 'warning',
        })
    }
}

// 上传文件改变的时候
const ChangeUpdate = (UploaFild,UploaFilds) => {
    file.value.clearFiles()
}
// 图片上传
const uploadImg = (option) => {
    // 定义一个图片上传文件
    let formData = new FormData()
    formData.append("image",option.file)
    http.post('/upload/upload',formData).then(res=>{
        console.log(res.data.data);
        info.value.image = res.data.data.path
    })
}
</script>

<style scoped>
.search{
    margin-top: 20px;
}
.search-details {
    display: flex;
}

.search-details label {
    margin-left: 30px;
    color: #999;
}

.container{
    margin: 30px;
    margin-top: 50px;
}

label .el-input,
label .el-select {
    margin-left: 10px;
    width: 200px;
}

label .el-select {
    margin-right: 30px;
}

.page {
    display: flex;
    justify-content: center;
}

.inp{
    width: 200px;
}
.el-upload img {
    width: 178px;
    height: 178px;
  }
</style>